from django.shortcuts import render
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin

from .models import Area
from .serializers import AreaSerializer, SubSerializer

# Create your views here.


class AreaViewSet(ReadOnlyModelViewSet, CacheResponseMixin):
    """
    请求省、市、区数据
    GET /areas/
    GET /areas/(?P<pk>\d+)/
    """
    # 关闭分页处理
    pagination_class = None

    def get_queryset(self):
        # 提供数据集
        if self.action == 'list':
            # 获取省份数据
            return Area.objects.filter(parent_id=None)
        else:
            # 获取市、区数据
            return Area.objects.all()

    def get_serializer_class(self):
        # 提供序列化器
        if self.action == 'list':
            return AreaSerializer
        else:
            return SubSerializer
